﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Xml;

using Ext.Net;
using System.Collections.Generic;

public partial class Popup_Popup_Cost1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.cbxGubun.Items.Add(new Ext.Net.ListItem("공재액", "N"));
            this.cbxGubun.Items.Add(new Ext.Net.ListItem("공재후실지불액", "Y"));
            this.cbxGubun.SelectedIndex = 0;

            SetStr();
            SetGridUp();
        }
    }

    private void SetStr()
    {
        try
        {
            using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
            {
                DataSet ds = null;

                //ds = oService.Select_SP_D_GYOUNGBI_S(1, this.cbxGubun.SelectedItem.Value.ToString());
                ds = oService.SELECT_D_ITEM_COST_BUNRU_S();
                this.StrBiz.DataSource = ds.Tables[0];
                this.StrBiz.DataBind();
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    protected void CreateParameter1(object sender, DirectEventArgs e)
    {
        string json = e.ExtraParams["Values"];

        Dictionary<string, string>[] dicValues = JSON.Deserialize<Dictionary<string, string>[]>(json);
        string strVal = string.Empty;

        foreach (Dictionary<string, string> dic in dicValues)
        {
            foreach (KeyValuePair<string, string> row in dic)
            {
                strVal += row.Value + "|";
            }
        }

        strVal = strVal.Remove(strVal.Length - 1);
        hdRowValue.Text = strVal;

        if (!string.IsNullOrEmpty(strVal.Split('|')[1]))
        {
            SetGridDown(int.Parse(strVal.Split('|')[1]));
        }
    }

    protected void CreateParameter2(object sender, DirectEventArgs e)
    {
        string json = e.ExtraParams["Values"];

        Dictionary<string, string>[] dicValues = JSON.Deserialize<Dictionary<string, string>[]>(json);
        string strVal = string.Empty;

        foreach (Dictionary<string, string> dic in dicValues)
        {
            foreach (KeyValuePair<string, string> row in dic)
            {
                strVal += row.Value + "|";
            }
        }

        strVal = strVal.Remove(strVal.Length - 1);
        hdRowValue2.Text = strVal;
    }

    private void SetGridUp()
    {
        using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
        {
            DataSet ds = null;

            this.Store1.RemoveAll();
            this.Store2.RemoveAll();

            //ds = oService.Select_SP_D_GYOUNGBI_S(1, this.cbxGubun.SelectedItem.Value.ToString());
            ds = oService.Select_SP_D_GYOUNGBI_S(1, this.cbxGubun.Items[0].Value);
            this.Store1.DataSource = ds.Tables[0];
            this.Store1.DataBind();
        }
    }

    private void SetGridDown(int kind)
    {
        try
        {
            using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
            {
                DataSet ds = null;

                this.Store2.RemoveAll();

                ds = oService.Select_D_GYOUNGBI_SMALL_S(0, kind, this.cbxGubun.SelectedItem.Value.ToString());
                this.Store2.DataSource = ds.Tables[0];
                this.Store2.DataBind();

                this.Store2.DataSource = ds;
                this.Store2.DataBind();
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }


    protected void cbxGubun_Change(object sender, DirectEventArgs e)
    {
        try
        {
            using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
            {
                DataSet ds = null;

                this.Store1.RemoveAll();
                this.Store2.RemoveAll();

                ds = oService.Select_SP_D_GYOUNGBI_S(1, this.cbxGubun.SelectedItem.Value.ToString());
                this.Store1.DataSource = ds.Tables[0];
                this.Store1.DataBind();
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }


    #region == Store_BeforeChanged(Store1 데이터가 변경되기전, 즉 Store에 들어오는 변경데이터를 파라미터로 보내옴) ==
    /// <summary>
    /// 실제 저장하는 이벤트
    /// Store1_BeforeChanged(Store1 데이터가 변경되기전, 즉 Store에 들어오는 변경데이터를 파라미터로 보내옴)
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Store_BeforeChanged(object sender, BeforeStoreChangedEventArgs e)
    {
        int nResult = 0;
        DataSet dsSave = null;
        try
        {
            Store oStore = sender as Store;
            if (oStore != null)
            {
                dsSave = this.GetXmlDocumentToSaveDataSet(e.DataHandler.XmlData);

                #region == 저장 Status 표시 ==
                //저장 메시지
                X.Msg.Show(new MessageBoxConfig
                {
                    Message = "저장 중입니다..잠시만 기다려주십시오..",
                    ProgressText = "Saving...",
                    Width = 300,
                    Wait = true,
                    WaitConfig = new WaitConfig { Interval = 150 },
                    IconCls = "ext-mb-download",
                    //AnimEl = Store1.ClientID
                });
                #endregion

                using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
                {
                    switch (oStore.ID)
                    {
                        case "Store1": //대분류
                            nResult = oService.SAVE_D_GYOUNGBI_IUD(dsSave);
                            SetGridUp();
                            break;
                        case "Store2": //소분류
                            if (!string.IsNullOrEmpty(this.hdRowValue.Text.Split('|')[1]))
                            {
                                nResult = oService.SAVE_D_GYOUNGBI_SMALL_IUD(dsSave, int.Parse(this.hdRowValue.Text.Split('|')[1]), this.cbxGubun.SelectedItem.Value);
                                SetGridDown(int.Parse(this.hdRowValue.Text.Split('|')[1]));
                            }
                            break;
                    }
                    
                }

                #region == 저장확인 메시지 ==
                //저장확인 메시지
                if (nResult > 0)
                {
                    this.ResourceManager1.AddScript("setTimeout(function () { Ext.MessageBox.hide(); Ext.Msg.notify('알림', '저장되었습니다.'); }, 500);");
                }
                #endregion
            }
            else
            {
                //Store가 아닐경우 pass
            }

        }
        catch (Exception ex)
        {
            this.ResourceManager1.AddScript("setTimeout(function () { Ext.MessageBox.hide(); Ext.Msg.notify('알림', '저장에 실패했습니다. 잠시후 다시 시도해주십시오.'); }, 500);");
            throw ex;
        }

    }

    /// <summary>
    /// Store에서 넘어오는Xmldocument를 저장 Dataset으로 반환
    /// </summary>
    /// <param name="pXd"></param>
    /// <returns></returns>
    private DataSet GetXmlDocumentToSaveDataSet(XmlDocument pXd)
    {
        DataSet dsReturn = new DataSet();

        using (System.Xml.XmlReader reader = new XmlNodeReader(pXd))
        {
            DataSet dsData = new DataSet();
            dsData.ReadXml(reader);
            reader.Close();
            dsReturn.Tables.Add(dsData.Tables[1].Copy());
            dsReturn.AcceptChanges();
        }
        return dsReturn;
    }
    #endregion
}